package cn.shop.merchant.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.shop.merchant.mapper.user.MerchantPermissionMapper;
import cn.shop.merchant.mapper.user.MerchantRoleMapper;
import cn.shop.merchant.model.user.AdminMenuVO;
import cn.shop.merchant.model.user.MerchantPermission;
import cn.shop.merchant.model.user.MerchantRole;
import cn.shop.merchant.req.AssignPermissionReq;
import cn.shop.utils.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 李一涵
 * @date : Created in 2021-11-11 14:24
 * @description :
 */
@Service
public class MerchantPermissionService extends BaseServiceImpl<MerchantPermissionMapper, MerchantPermission> {

	@Resource
	private MerchantRoleMapper roleMapper;

	/**
	 * 新增数据
	 *
	 * @param permission 实体对象
	 * @return 新增结果
	 * @author jy
	 * @since 2022-01-17 15:47:07
	 */
	public Boolean insert(MerchantPermission permission) {
		LambdaQueryWrapper<MerchantPermission> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(MerchantPermission::getCode, permission.getCode());
		MerchantPermission exist = baseMapper.selectOne(queryWrapper);
		if (exist != null) {
			throw new ServiceException("当前权限code已存在!");
		}
		permission.setEnable(true);
		permission.setInitial(false);
		return SqlHelper.retBool(baseMapper.insert(permission));
	}

	/**
	 * 修改数据
	 *
	 * @param permission 实体对象
	 * @return 修改结果
	 * @author jy
	 * @since 2022-01-17 15:47:07
	 */
	public boolean update(MerchantPermission permission) {
		LambdaQueryWrapper<MerchantPermission> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(MerchantPermission::getCode, permission.getCode()).ne(MerchantPermission::getId, permission.getId());
		MerchantPermission exist = baseMapper.selectOne(queryWrapper);
		if (exist != null) {
			throw new ServiceException("当前权限code已存在!");
		}
		return SqlHelper.retBool(baseMapper.updateById(permission));
	}

	/**
	 * 分配权限
	 *
	 * @param req 前台参数
	 * @return 分配结果
	 */
	public boolean assignPermissions(AssignPermissionReq req, long uid) {
		List<Long> checkList = req.getCheckList();
		List<Long> halfList = req.getHalfList();
		Long id = req.getRoleId();
		//将半选和全选封装到一起
		List<Map<String, Object>> dataList = new LinkedList<>();
		checkList.forEach(ele -> {
			Map<String, Object> dataMap = new HashMap<>(3);
			dataMap.put("permissionId", ele);
			dataMap.put("roleId", id);
			dataMap.put("checked", true);
			dataMap.put("uid", uid);
			dataList.add(dataMap);
		});
		halfList.forEach(ele -> {
			Map<String, Object> dataMap = new HashMap<>(3);
			dataMap.put("permissionId", ele);
			dataMap.put("roleId", id);
			dataMap.put("checked", false);//表示半选
			dataMap.put("uid", uid);
			dataList.add(dataMap);
		});
		if (dataList.isEmpty()) {
			return false;
		}

		baseMapper.removePermissionByRoleId(req.getRoleId(), uid);
		boolean res = SqlHelper.retBool(baseMapper.assignPermission(dataList));
		if (res) {
			MerchantRole role = roleMapper.selectOne(Wrappers.<MerchantRole>lambdaQuery()
					.eq(MerchantRole::getId, req.getRoleId()));
			SaSession session = SaSessionCustomUtil.getSessionById("role-" + role.getCode(), false);
			if (null != session) {
				session.delete("Permission_List");
			}
		}
		return res;
	}


	/**
	 * 查询所有权限树
	 *
	 * @return 查询结果
	 */
	public List<MerchantPermission> allPermissionTree() {
		LambdaQueryWrapper<MerchantPermission> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(MerchantPermission::getEnable, true).orderByAsc(MerchantPermission::getSort);
		List<MerchantPermission> permissions = baseMapper.selectList(queryWrapper);
		Map<Long, List<MerchantPermission>> collect = permissions.stream().collect(Collectors.groupingBy(MerchantPermission::getParentId));

		List<MerchantPermission> parent = collect.get(0L);
		parse(parent, collect);
		return parent;
	}

	/**
	 * 递归拼接菜单
	 */
	private void parse(List<MerchantPermission> parent, Map<Long, List<MerchantPermission>> permissions) {
		for (MerchantPermission permission : parent) {
			Long id = permission.getId();
			List<MerchantPermission> children = permissions.get(id);
			if (CollectionUtil.isNotEmpty(children)) {
				permission.setPChild(children);
				parse(children, permissions);
			}
		}
	}

	/**
	 * 根据用户id查询权限树
	 *
	 * @param userId 用户编号
	 * @return 查询结果
	 */
	public List<AdminMenuVO> userPermissionTree(long userId, long uid) {
		List<AdminMenuVO> menuList = baseMapper.allPermissionByUserId(userId);
		if (menuList.size() == 0) {
			return Collections.emptyList();
		}
		Map<Long, List<AdminMenuVO>> collect = menuList.stream().collect(Collectors.groupingBy(AdminMenuVO::getParentId));
		List<AdminMenuVO> parent = collect.get(0L);
		parseList(parent, collect);
		return parent;
	}

	/**
	 * 递归拼接菜单
	 */
	private void parseList(List<AdminMenuVO> parent, Map<Long, List<AdminMenuVO>> permissions) {
		for (AdminMenuVO adminMenuVO : parent) {
			Long id = adminMenuVO.getPermissionId();
			List<AdminMenuVO> children = permissions.get(id);
			if (CollectionUtil.isNotEmpty(children)) {
				adminMenuVO.setSubMenu(children);
				parseList(children, permissions);
			}
		}
	}


}
